package gov.pbc.gx.nn.pz.impl;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.imageio.ImageIO;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.bstek.bdf2.core.business.IUser;
import com.bstek.bdf2.core.context.ContextHolder;
import com.bstek.bdf2.core.exception.NoneLoginException;
import com.bstek.dorado.annotation.DataProvider;
import com.bstek.dorado.annotation.DataResolver;
import com.bstek.dorado.annotation.Expose;
import com.bstek.dorado.data.variant.Record;
import com.bstek.dorado.web.DoradoContext;

import gov.pbc.gx.nn.pz.dao.TzckywTzsqdDao;
import gov.pbc.gx.nn.pz.entity.HcTzckywTzsqd;
import gov.pbc.gx.nn.pz.entity.HcpzXY;
import gov.pbc.gx.nn.pz.entity.PzFont;

/**
 * 
 * @author charles.cao 本类主要实现tzckywtzsqb业务逻辑的操作
 * 
 */

@Component("tzckywtzsqbPR")
public class TzckywtzsqbPR {
	@Resource
	@Autowired
	private TzckywTzsqdDao tzckywTzsqdDao;

	private Integer PZ_CODE_ = 3;
	private static final Integer Font_Size = 16;

	@Transactional
	@DataProvider
	public Record getTzckywpz() {
		try {
			IUser loginuser = ContextHolder.getLoginUser();
			if (loginuser == null)
				return null;
			if (loginuser.getDepts() == null || loginuser.getDepts().size() <= 0)
				return null;
			Record record = new Record();
			record.put("pzdate", new Date());
			Collection<HcTzckywTzsqd> lists = tzckywTzsqdDao.getMuByDeptName();
			if (lists.isEmpty()) {
				HcTzckywTzsqd e = new HcTzckywTzsqd();
				e.setPzDate(new Date());
				e.setPzTemplate("新建模板");
				e.setErrorValueIsSign(1);
				e.setTzValueIsSign(1);
				lists.add(e);
				record.put("tzckywpz", lists);
			} else {
				for (HcTzckywTzsqd hcTzckywTzsqd : lists) {
					hcTzckywTzsqd.setPzDate(new Date());
				}
				record.put("tzckywpz", lists);
			}

			List<HcpzXY> xjpzXYs = tzckywTzsqdDao.getHcPzXYs(PZ_CODE_);
			if (xjpzXYs != null && !xjpzXYs.isEmpty()) {
				record.put("pys", xjpzXYs);
			} else {
				xjpzXYs = new ArrayList<HcpzXY>();
				HcpzXY xjpzXY = new HcpzXY();
				xjpzXY.setProperty("页边距", 50, 50, Font_Size);
				xjpzXYs.add(xjpzXY);

				xjpzXY = new HcpzXY();
				xjpzXY.setId(UUID.randomUUID().toString());
				xjpzXY.setProperty("年", 255, 68, Font_Size);
				xjpzXYs.add(xjpzXY);

				xjpzXY = new HcpzXY();
				xjpzXY.setProperty("月", 325, 68, Font_Size);
				xjpzXYs.add(xjpzXY);

				xjpzXY = new HcpzXY();
				xjpzXY.setProperty("日", 385, 68, Font_Size);
				xjpzXYs.add(xjpzXY);

				// xjpzXY = new HcpzXY();
				// xjpzXY.setProperty("流水号", 560, 68);
				// xjpzXYs.add(xjpzXY);
				xjpzXY = new HcpzXY();
				xjpzXY.setProperty("原业务流水号", 120, 100, 13);
				xjpzXYs.add(xjpzXY);
				xjpzXY = new HcpzXY();
				xjpzXY.setProperty("错误值", 120, 145, Font_Size);
				xjpzXYs.add(xjpzXY);
				xjpzXY = new HcpzXY();
				xjpzXY.setProperty("调整值", 450, 145, Font_Size);
				xjpzXYs.add(xjpzXY);
				xjpzXY = new HcpzXY();
				xjpzXY.setProperty("调整说明", 120, 340, Font_Size);
				xjpzXYs.add(xjpzXY);
				xjpzXY = new HcpzXY();
				xjpzXY.setProperty("附件数量", 700, 250, Font_Size);
				xjpzXYs.add(xjpzXY);

				xjpzXY = new HcpzXY();
				xjpzXY.setProperty("金额错误", 125, 205, Font_Size);
				xjpzXYs.add(xjpzXY);

				xjpzXY = new HcpzXY();
				xjpzXY.setProperty("错误日期", 485, 100, Font_Size);
				xjpzXYs.add(xjpzXY);

				xjpzXY = new HcpzXY();
				xjpzXY.setProperty("利率错误", 455, 205, Font_Size);
				xjpzXYs.add(xjpzXY);

				xjpzXY = new HcpzXY();
				xjpzXY.setProperty("账号错误", 125, 248, Font_Size);
				xjpzXYs.add(xjpzXY);

				xjpzXY = new HcpzXY();
				xjpzXY.setProperty("日期错误", 455, 248, Font_Size);
				xjpzXYs.add(xjpzXY);

				xjpzXY = new HcpzXY();
				xjpzXY.setProperty("其他错误", 125, 292, Font_Size);
				xjpzXYs.add(xjpzXY);
			}

			record.put("pys", xjpzXYs);
			// record.put("pym", pym);
			//
			// PzFont pzFont = tzckywTzsqdDao.getFont(PZ_CODE_);
			// if (pzFont == null) {
			// record.put("fontzh", "新宋体");
			// record.put("fonten", "微软雅黑");
			// record.put("fontid", null);
			// } else {
			// record.put("fontzh", pzFont.getCnFont());
			// record.put("fonten", pzFont.getNumFont());
			// record.put("fontid", pzFont.getId());
			// }

			return record;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	@SuppressWarnings("unchecked")
	public void setImageData(Graphics2D graphics, Map<String, Object> param) {
		HcTzckywTzsqd hcTzckywTzsqd = (HcTzckywTzsqd) param.get("tzckywpz");
		Date pzdate = (Date) param.get("pzdate");
		int pyx = (int) Integer.parseInt(param.get("x").toString());
		int pyy = (int) Integer.parseInt(param.get("y").toString());
		String fontzh = param.get("fontzh").toString();
		String fonten = param.get("fonten").toString();

		// int pyx = 0, pyy = 0;
		// Map<String, Object> pym = (Map<String, Object>) param.get("pym");
		graphics.setBackground(Color.WHITE);
		graphics.setColor(Color.BLACK);
		// Font zhFont = new Font(fontzh, Font.PLAIN, 16);
		// Font enFont = new Font(fonten, Font.PLAIN, 16);
		// Font lshFont = new Font(fonten, Font.PLAIN, 13);
		List<HcpzXY> hcpzxys = (List<HcpzXY>) param.get("pys");
		for (HcpzXY hcpzXY : hcpzxys) {
			int x = hcpzXY.getX() + pyx;
			int y = hcpzXY.getY() + pyy;
			int size = hcpzXY.getFontSize();
			String lable = hcpzXY.getLabel();
			if (pzdate != null) {
				Calendar calendar = Calendar.getInstance();
				calendar.setTime(pzdate);
				if (lable.equals("年")) {
					Font enFont = new Font(fonten, Font.PLAIN, size);
					graphics.setFont(enFont);
					graphics.drawString(String.format("%04d", calendar.get(Calendar.YEAR)), x, y - 10);
				}
				if (lable.equals("月")) {
					Font enFont = new Font(fonten, Font.PLAIN, size);
					graphics.setFont(enFont);
					graphics.drawString(String.format("%02d", calendar.get(Calendar.MONTH) + 1), x, y - 10);
				}
				if (lable.equals("日")) {
					Font enFont = new Font(fonten, Font.PLAIN, size);
					graphics.setFont(enFont);
					graphics.drawString(String.format("%02d", calendar.get(Calendar.DATE)), x, y - 10);
				}
			}
			if (hcTzckywTzsqd != null) {
				if (lable.equals("原业务流水号")) {
					if (hcTzckywTzsqd.getPrimarySerialnumber() != null) {
						Font enFont = new Font(fonten, Font.PLAIN, size);
						graphics.setFont(enFont);
						graphics.drawString(hcTzckywTzsqd.getPrimarySerialnumber(), x, y - 10);
					}
				}
				if (lable.equals("错误日期")) {
					if (hcTzckywTzsqd.getDateWrong() != null) {
						Font enFont = new Font(fonten, Font.PLAIN, size);
						graphics.setFont(enFont);
						Calendar calendar = Calendar.getInstance();
						calendar.setTime(hcTzckywTzsqd.getDateWrong());
						graphics.drawString(String.format("%04d", calendar.get(Calendar.YEAR)), x, y - 10);
						graphics.drawString(String.format("%02d", calendar.get(Calendar.MONTH) + 1), x + 75, y - 10);
						graphics.drawString(String.format("%02d", calendar.get(Calendar.DATE)), x + 125, y - 10);
					}
				}
				if (lable.equals("错误值")) {
					if (hcTzckywTzsqd.getErrorValue() != null) {
						Font enFont = new Font(fonten, Font.PLAIN, size);
						graphics.setFont(enFont);
						DecimalFormat myformat = new DecimalFormat();
						myformat.applyPattern("##,###.00");
						String errorValue = myformat.format(hcTzckywTzsqd.getErrorValue());
						// if (hcTzckywTzsqd.getErrorValueIsSign() ==null) {
						// graphics.drawString(errorValue, x, y - 10);
						// }
						if (hcTzckywTzsqd.getErrorValueIsSign() == 1) {
							graphics.drawString("¥ " + errorValue, x, y - 10);
						}
						if (hcTzckywTzsqd.getErrorValueIsSign() == 2) {
							graphics.drawString("HKD " + errorValue, x, y - 10);
						}
						if (hcTzckywTzsqd.getErrorValueIsSign() == 3) {
							graphics.drawString("USD " + errorValue, x, y - 10);
						}
						if (hcTzckywTzsqd.getErrorValueIsSign() == 4) {
							graphics.drawString(errorValue, 30 + x, y - 10);
						}
					}
				}
				if (lable.equals("调整值")) {
					if (hcTzckywTzsqd.getTzValue() != null) {
						Font enFont = new Font(fonten, Font.PLAIN, size);
						graphics.setFont(enFont);
						DecimalFormat myformat = new DecimalFormat();
						myformat.applyPattern("##,###.00");
						String TzValue = myformat.format(hcTzckywTzsqd.getTzValue());
						if (hcTzckywTzsqd.getTzValueIsSign() == 1) {
							graphics.drawString("¥ " + TzValue, x, y - 10);
						}
						if (hcTzckywTzsqd.getTzValueIsSign() == 2) {
							graphics.drawString("HKD " + TzValue, x, y - 10);
						}
						if (hcTzckywTzsqd.getTzValueIsSign() == 3) {
							graphics.drawString("UKD " + TzValue, x, y - 10);
						}
						if (hcTzckywTzsqd.getTzValueIsSign() == 4) {
							graphics.drawString(TzValue, 30 + x, y - 10);
						}
					}
				}
				if (lable.equals("调整说明")) {
					if (hcTzckywTzsqd.getTzCaption() != null) {
						Font zhFont = new Font(fontzh, Font.PLAIN, size);
						graphics.setFont(zhFont);
						graphics.drawString(hcTzckywTzsqd.getTzCaption(), x, y - 10);
					}
				}
				if (lable.equals("附件数量")) {
					if (hcTzckywTzsqd.getAttachmentCount() != null) {
						Font enFont = new Font(fonten, Font.PLAIN, size);
						graphics.setFont(enFont);
							graphics.drawString(String.valueOf(hcTzckywTzsqd.getAttachmentCount()), x, y - 10);
					}
				}
				if (lable.equals("金额错误")) {
					if (hcTzckywTzsqd.getErrorMoney() != null) {
						String[] nums = hcTzckywTzsqd.getErrorMoney().split(",");
						String click = "√";
						if (nums[0].equals("1")) {
							Font enFont = new Font(fonten, Font.PLAIN, size);
							graphics.setFont(enFont);
							graphics.drawString(click, x - 2, y - 10);
						}
						if (nums[1].equals("1")) {
							Font enFont = new Font(fonten, Font.PLAIN, size);
							graphics.setFont(enFont);
							graphics.drawString(click, 111 + x, y - 10);
						}
					}
				}

				if (lable.equals("利率错误")) {
					if (hcTzckywTzsqd.getErrorLl() != null) {
						String[] nums = hcTzckywTzsqd.getErrorLl().split(",");
						String click = "√";
						if (nums[0].equals("1")) {
							Font enFont = new Font(fonten, Font.PLAIN, size);
							graphics.setFont(enFont);
							graphics.drawString(click, x - 3, y - 10);
						}
						if (nums[1].equals("1")) {
							Font enFont = new Font(fonten, Font.PLAIN, size);
							graphics.setFont(enFont);
							graphics.drawString(click, 115 + x, y - 10);
						}
					}
				}
				if (lable.equals("账号错误")) {
					if (hcTzckywTzsqd.getErrorAccount() != null) {
						String[] nums = hcTzckywTzsqd.getErrorAccount().split(",");
						String click = "√";
						if (nums[0].equals("1")) {
							Font enFont = new Font(fonten, Font.PLAIN, size);
							graphics.setFont(enFont);
							graphics.drawString(click, x - 2, y - 9);
						}
					}
				}
				if (lable.equals("日期错误")) {
					if (hcTzckywTzsqd.getErrorDate() != null) {
						String[] nums = hcTzckywTzsqd.getErrorDate().split(",");
						String click = "√";
						if (nums[0].equals("1")) {
							Font enFont = new Font(fonten, Font.PLAIN, size);
							graphics.setFont(enFont);
							graphics.drawString(click, x - 3, y - 10);
						}
					}
				}
				if (lable.equals("其他错误")) {
					if (hcTzckywTzsqd.getErrorOrther() != null) {
						String[] nums = hcTzckywTzsqd.getErrorOrther().split(",");
						String click = "√";
						if (nums[0].equals("1")) {
							Font enFont = new Font(fonten, Font.PLAIN, size);
							graphics.setFont(enFont);
							graphics.drawString(click, x - 3, y - 10);
						}
						if (nums[1].equals("1")) {
							Font enFont = new Font(fonten, Font.PLAIN, size);
							graphics.setFont(enFont);
							graphics.drawString(click, 75 + x, y - 10);
						}
						if (nums[2].equals("1")) {
							Font enFont = new Font(fonten, Font.PLAIN, size);
							graphics.setFont(enFont);
							graphics.drawString(click, 177 + x, y - 10);
						}
						if (nums[3].equals("1")) {
							Font enFont = new Font(fonten, Font.PLAIN, size);
							graphics.setFont(enFont);
							graphics.drawString(click, 279 + x, y - 10);
						}
					}
				}

			}

		}

	}

	@Expose
	public String getPrintImageAll(Map<String, Object> param) {
		try {
			if (param == null)
				return null;
			IUser loginuser = ContextHolder.getLoginUser();
			if (loginuser == null)
				throw new NoneLoginException("您未登录，请刷新页面后重试！！");
			param.put("x", 0);
			param.put("y", 0);
			BufferedImage imagepz = ImageIO.read(new File(DoradoContext.getCurrent().getServletContext().getRealPath("pz/tzckywtzsqd.jpg")));
			Graphics2D graphicspz = (Graphics2D) imagepz.getGraphics();
			setImageData(graphicspz, param);
			// ByteArrayOutputStream bytestreampz=new ByteArrayOutputStream();
			String filename = "pz/temp/all_" + loginuser.getUsername() + ".jpg";
			FileOutputStream fo = new FileOutputStream(new File(DoradoContext.getCurrent().getServletContext().getRealPath(filename)));
			ImageIO.write(imagepz, "jpg", fo);
			fo.flush();
			fo.close();
			// String
			// str="data:image/png;base64,"+Base64.encodeBase64String(bytestreampz.toByteArray());
			// System.out.println(str.length()+","+bytestreampz.toByteArray().length);
			return filename;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return null;
		}
	}

	@Expose
	public String getPrintImageData(Map<String, Object> param) {
		try {
			if (param == null)
				return null;
			IUser loginuser = ContextHolder.getLoginUser();
			if (loginuser == null)
				throw new NoneLoginException("您未登录，请刷新页面后重试！！");
			param.put("x", -31);
			param.put("y", -27);
			BufferedImage imagedata = ImageIO.read(new File(DoradoContext.getCurrent().getServletContext().getRealPath("pz/tzckywtzsqd.jpg")));
			// System.out.println(imagepz.getWidth()*1.0/96.0*24.5);
			// BufferedImage imagedata= new BufferedImage(imagepz.getWidth(),
			// imagepz.getHeight(), imagepz.getType());
			Graphics2D graphicsdata = (Graphics2D) imagedata.getGraphics();
			graphicsdata.setBackground(Color.WHITE);

			// 打印背景图片
			graphicsdata.clearRect(0, 0, imagedata.getWidth(), imagedata.getHeight());
			setImageData(graphicsdata, param);
			// ByteArrayOutputStream bytestreampz=new ByteArrayOutputStream();
			String filename = "pz/temp/data_" + loginuser.getUsername() + ".jpg";
			FileOutputStream fo = new FileOutputStream(new File(DoradoContext.getCurrent().getServletContext().getRealPath(filename)));
			ImageIO.write(imagedata, "jpg", fo);
			fo.flush();
			fo.close();
			// String
			// str="data:image/png;base64,"+Base64.encodeBase64String(bytestreampz.toByteArray());
			// System.out.println(str.length()+","+bytestreampz.toByteArray().length);
			return filename;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return null;
		}
	}

	@Expose
	public Map<String, Object> getUserInfo() {
		IUser loginuser = ContextHolder.getLoginUser();
		Map<String, Object> userinfo = new HashMap<String, Object>();
		if (loginuser == null) {
			userinfo.put("cname", "");
			userinfo.put("dept", "");
			return userinfo;
		}
		userinfo.put("cname", loginuser.getCname());
		if (loginuser.getDepts() == null || loginuser.getDepts().size() <= 0) {
			userinfo.put("dept", "");
			return userinfo;
		}
		userinfo.put("dept", loginuser.getDepts().get(0).getName());
		return userinfo;
	}

	@DataProvider
	public Collection<HcTzckywTzsqd> getTypeByGroup() {
		return tzckywTzsqdDao.getOneGroupByType();
	}

	@DataProvider
	public Collection<HcTzckywTzsqd> getTepementNameByType(Map<String, Object> param) {
		if (param == null) {
			return null;
		}
		String type = (String) param.get("type");
		return tzckywTzsqdDao.getCoByType(type);
	}

	@Expose
	public HcTzckywTzsqd ajaxselectOneByTypeAndTemplate(Map<String, Object> param) {
		String type = (String) param.get("type");
		String pzTemplate = (String) param.get("pzTemplate");
		if (type == null || pzTemplate == null) {
			return null;
		}
		return tzckywTzsqdDao.selectOneByTypeAndTemplate(type, pzTemplate);

	}

	@DataProvider
	public List<Record> getFonts() {
		return tzckywTzsqdDao.getFonts();
	}

	@DataProvider
	public PzFont getFont() {
		return tzckywTzsqdDao.getFont(PZ_CODE_);
	}

	@Transactional
	@DataResolver
	public void saveXjpz(HcTzckywTzsqd hcTzckywTzsqd) {
		tzckywTzsqdDao.saveXjpz(hcTzckywTzsqd);
	}

	@Transactional
	@DataResolver
	public void saveXjpzXY(Collection<HcpzXY> hcXjpzXY) {
		tzckywTzsqdDao.saveXjpzXY(hcXjpzXY);
	}

	// @Expose
	// public void saveFont(Map<String, Object> param) throws Exception {
	// tzckywTzsqdDao.updateFont(pzfont);
	// }
	//
	@Transactional
	@DataResolver
	public void saveFont(PzFont pzFont) throws Exception {
		tzckywTzsqdDao.updateFont(pzFont);
	}

	@Expose
	public void deleteTemplateById(String id) {
		if (StringUtils.isNotEmpty(id)) {
			tzckywTzsqdDao.deleteTemplateById(id);
		}
	}

	@Expose
	public boolean updateTempalteName(Map<String, Object> parameter) {
		String id = (String) parameter.get("id");
		String pzTemplate = (String) parameter.get("pzTemplate");
		return tzckywTzsqdDao.updateTemplateNameDao(pzTemplate, id);
	}

	@Expose
	public boolean updateTempalteType(Map<String, Object> parameter) {
		String id = (String) parameter.get("id");
		String type = (String) parameter.get("type");
		return tzckywTzsqdDao.updateTemplateTypeDao(type, id);
	}
}
